<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" class="add" @click="addUser">新增</el-button>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        class="table"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户名" align="center" width="200">
          <template v-slot="{ row }">
            <div class="block">
              <el-input
                v-if="row.isEdit"
                v-model="row.editRow.username"
              ></el-input>
              <span v-else>{{ row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="头像" align="center" width="160">
          <template slot-scope="scope">
            <div class="block">
              <el-avatar
                v-if="scope.row.image"
                :size="50"
                :src="scope.row.image"
                >{{ scope.row.username.charAt(0) }}</el-avatar
              >
              <span v-else class="username">{{
                scope.row.username.charAt(0)
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" width="160">
          <template v-slot="{ row }">
            <div class="block">
              <el-input
                v-if="row.isEdit"
                v-model="row.editRow.phoneNumber"
              ></el-input>
              <span v-else>{{ row.phoneNumber }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="160">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-switch
                v-model="row.editRow.isEnabled"
                active-color="#13ce66"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </template>
            <template v-else>
              <el-tag :type="statusType(row.isEnabled)" size="medium">{{
                row.isEnabled ? "启用" : "未启用"
              }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="角色" prop="roleId" align="center" width="160">
          <template v-slot="{ row }">
            <el-select
              v-model="row.editRow.roleId"
              placeholder="请选择"
              v-if="row.isEdit"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <span v-else>{{ roleName(row.roleId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="200">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{
              leaveTime(scope.row.createTime)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" width="200">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{
              leaveTime(scope.row.updateTime)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280" fixed="right">
          <template v-slot="{ row, $index }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="btnConfirm(row)"
                >确定</el-button
              >
              <el-button size="mini" @click="btnCancel(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" @click="handleEdit(row)">编辑</el-button>
              <el-button
                size="mini"
                type="primary"
                @click="handlePermission(row)"
                >权限分配</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(row)"
                :disabled="$index < 3"
                >删除</el-button
              >
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      width="500px"
      title="新增用户"
      @close="cancel"
      :visible.sync="showDialog"
    >
      <el-form
        ref="usersForm"
        label-width="100px"
        :model="usersForm"
        :rules="rules"
      >
        <el-form-item prop="username" label="用户名">
          <el-input
            clearable
            placeholder="请输入用户名"
            style="width: 300px"
            v-model="usersForm.username"
          />
        </el-form-item>
        <!-- name 用于定义上传字段的名字 -->
        <el-form-item prop="image" label="头像">
          <el-upload
            name="image"
            class="avatar-uploader"
            :headers="avatarAction.headers"
            :action="avatarAction.url"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
          >
            <el-image
              v-if="usersForm.image"
              :src="usersForm.image"
              class="avatar"
            >
              <div slot="placeholder" class="image-slot">
                加载中<span class="dot">...</span>
              </div>
            </el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="phoneNumber" label="电话">
          <el-input
            clearable
            placeholder="请输入电话"
            style="width: 300px"
            v-model="usersForm.phoneNumber"
          />
        </el-form-item>
        <el-form-item prop="roleId" label="角色">
          <el-select v-model="usersForm.roleId" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-row type="flex">
            <el-col :push="12">
              <el-button type="primary" @click="submitForm('usersForm')"
                >确定</el-button
              >
              <el-button @click="cancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :visible.sync="showPermissionDetail"
      title="权限分配"
      width="500px"
      @close="closepermission"
    >
      <el-tag
        :key="tag"
        v-for="tag in permissionNames"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)"
      >
        {{ tag }}
      </el-tag>
      <el-input
        class="input-new-tag"
        v-if="inputVisible"
        v-model="inputValue"
        ref="saveTagInput"
        size="small"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
      >
      </el-input>
      <el-button v-else class="button-new-tag" size="small" @click="showInput"
        >+ New Tag</el-button
      >
    </el-dialog>
  </div>
</template>
<script>
import { getUsers, getRoles, getRolesDetails } from "@/api/role";
import { deleteUser, insertUser, updateUser } from "@/api/role";
import { getToken } from "@/utils/auth";
import moment from "moment";
export default {
  name: "Role",
  data() {
    return {
      inputVisible: false,
      inputValue: "",
      permissionIds: [], //权限列表id
      permissionNames: [], //权限列表name
      showPermissionDetail: false, // 权限分配
      showDialog: false, // 添加
      loading: true,
      tableData: [],
      // 上传头像对象
      avatarAction: {
        url: "/api/upload",
        headers: {
          token: getToken(),
        },
      },
      usersForm: {
        username: "",
        image: "",
        roleId: "",
        phoneNumber: "",
      },
      rules: {
        username: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur",
          },
        ],
        image: [
          {
            required: true,
            message: "头像不能为空",
            trigger: "blur",
          },
        ],
        roleId: [
          {
            required: true,
            message: "角色不能为空",
            trigger: "blur",
          },
        ],
        phoneNumber: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
      },
      options: [],
    };
  },
  created() {
    this.getUsersMsg();
    this.getRoles();
  },
  methods: {
    // 获取所有用户信息
    async getUsersMsg() {
      this.tableData = await getUsers();
      console.log(this.tableData);

      this.loading = false;
      this.tableData.forEach((element) => {
        this.$set(element, "isEdit", false);
      });
      this.tableData.forEach((i) => {
        this.$set(i, "editRow", {
          id: i.id,
          username: i.username,
          phoneNumber: i.phoneNumber,
          isEnabled: i.isEnabled,
          roleId: i.roleId,
        });
      });
    },
    // 获取角色
    async getRoles() {
      this.options = await getRoles();
    },

    // 删除用户
    handleDelete(row) {
      this.$confirm("是否删除该用户", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteUser(row.id).then((res) => {
            this.$message({
              message: "删除成功！",
              type: "success",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 新增用户
    addUser() {
      this.showDialog = true;
    },
    // 取消
    cancel() {
      this.$refs.usersForm.resetFields(); // 重置表单数据
      this.showDialog = false;
    },
    // 新增用户
    submitForm() {
      this.$refs.usersForm.validate(async (isOk) => {
        if (isOk) {
          await insertUser(this.usersForm);
          this.$message.success("新增用户成功");
          this.cancel();
          this.getUsersMsg();
        }
      });
    },
    // 上传头像成功后的回调
    handleAvatarSuccess(res, file) {
      this.usersForm.image = res.data;
    },
    // 取消
    btnCancel(row) {
      row.isEdit = false;
    },
    // 确认
    async btnConfirm(row) {
      if (row.editRow.username) {
        await updateUser(row.editRow).then((res) => {
          this.$message.success("更新用户数据成功");
          Object.assign(row, {
            ...row.editRow,
            isEdit: false,
          });
        });
      } else {
        this.$message.warning("用户名不能为空");
      }
    },
    // 编辑用户
    handleEdit(row) {
      row.isEdit = true;
      row.editRow.username = row.username;
      row.editRow.phoneNumber = row.phoneNumber;
      row.editRow.isEnabled = row.isEnabled;
      row.editRow.roleId = row.roleId;
    },
    // 权限分配
    async handlePermission(row) {
      const id = row.roleId;
      const permissions = await getRolesDetails(id);
      permissions.forEach((i) => {
        this.permissionIds.push(i.permissionId);
        this.permissionNames.push(i.permissionName);
      });
      this.showPermissionDetail = true;
    },
    statusType(status) {
      if (status) {
        return "success";
      } else {
        return "danger";
      }
    },
    // 转换日期格式
    leaveTime(value) {
      return moment(value).format("YYYY-MM-DD HH:mm");
    },
    // 角色转换
    roleName(id) {
      const roles = {
        1: "管理员",
        2: "供应商",
        3: "采购员",
      };
      return roles[id];
    },
    closepermission() {
      this.permissionNames = [];
    },
    handleClose(tag) {
      this.permissionNames.splice(this.permissionNames.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.permissionNames.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
  },
};
</script>

<style scoped>
.el-tag + .el-tag {
  margin: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.add {
  margin-bottom: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.username {
  font-size: 16px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  line-height: 30px;
  color: #fff;
  text-align: center;
  background-color: #04c9be;
  margin-right: 5px;
}
</style>
